<template>
    <div class="draftbox_container">
        <div class="draftbox_container_left">
            <OfficialList @submit="getOffcialId" />
        </div>
        <div class="draftbox_container_right">
            <ZwSearchForm row-num="2" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()">
                <template #headerOperate>
                    <el-button type="primary" @click="toCreate">新建草稿</el-button>
                </template>
            </ZwTable>
        </div>
    </div>
    <Dialog :app-dialog="appDialog">
        <div class="wrapper">
            <el-form>
                <el-form-item class="item_margin">
                    <div class="title">预览链接用于查看文章效果，需关注公众号后才可接收，链接会在短期内失效</div>
                    <el-select
                        v-model="state.preview_wx_user_id"
                        class="wx_select"
                        popper-class="wx_popper"
                        style="width: 100%"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        :reserve-keyword="false"
                        placeholder="可输入多个微信号回车分隔">
                        <!-- <el-option-group label="发送过的微信号">
              <el-option v-for="item in state.previewWxUserIdList" :key="item" :label="item" :value="item" />
            </el-option-group> -->
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
    </Dialog>
    <ZWDeletdialog ref="DeletdialogRef" @submit="onDelSubmit" />
</template>

<script setup lang="tsx">
import ArticleDetailItem from '../components/ArticleDetailItem.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import Dialog from '@/components/Dialog.vue';
import OfficialList from './components/OfficialList.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { getCreateList } from '@/api/common';

import {
    officialSync,
    getOfficialArticleList,
    againSendMass,
    previewOffical,
    delOfficalDraft
} from '@/api/content/channelFootage/officialaccountgraphics';
import { getOfficeAccountList } from '@/api/channelconfig/officeAccount';

import { ElMessage, ElImage, ElIcon, ElButton } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';

const router = useRouter();
const defaultParams = {
    type: 1, //草稿
    draft_title: '',
    create_time: [],
    created_uid: [],
    official_account_id: ''
};
const state = reactive({
    searchParams: deepCopy(defaultParams),
    syncTime: '', // 最近更新时间
    row: {},
    preview_wx_user_id: [], // 预览微信号
    previewWxUserIdList: [] // 发送过的微信号
});
const getOffcialId = (id: any) => {
    defaultParams.official_account_id = id;
    state.searchParams = { ...state.searchParams, official_account_id: id };
};

// 固定列高度统一
const onChangeCollapse = (index: number) => {
    const leftEls = tableRef.value.$el.querySelectorAll('.el-table__fixed .el-table__fixed-body-wrapper tbody tr')[
        index
    ];
    const rightEls = tableRef.value.$el.querySelectorAll(
        '.el-table__fixed-right .el-table__fixed-body-wrapper tbody tr'
    )[index];
    const targetRow = tableRef.value.$el.querySelectorAll('.el-table__body-wrapper tbody tr')[index];

    const setFixedRowHeight = setInterval(() => {
        const height = targetRow.getBoundingClientRect().height;
        if (leftEls) {
            leftEls.style.height = `${height}px`;
        }
        if (rightEls) {
            rightEls.style.height = `${height}px`;
        }
    }, 10);
    setTimeout(() => {
        if (setFixedRowHeight) {
            clearInterval(setFixedRowHeight);
        }
    }, 1000);
};

const tableRef: any = ref<any>(null);
const DeletdialogRef: any = ref(null);

const searchOption = computed(() => {
    return [
        {
            label: '草稿搜索',
            name: 'draft_title',
            value: '',
            type: 'input',
            placeholder: '请输入标题进行查找'
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            defaultTime: [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)],
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            type: 'select',
            placeholder: '请选择创建人',
            multiple: true,
            // popperClass: 'zw-hide_select_option',
            // isUserSelect: true,
            collapseTags: true,
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const arr = res.map((item: any) => ({ ...item, name: `${item.name}/${item.phone}` }));
                        resolve(arr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const search = (v: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v
    };
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
// 群发
const onQunFa = (row: any) => {
    againSendMass({ id: row.id, type: 1 })
        .then((resp: any) => {
            ElMessage.success('群发成功');
        })
        .finally(() => {
            reloadTable();
        });
};
// 预览
const onYuLan = (row: any) => {
    appDialog.visible = true;
    state.row = row;
};
// 编辑
const onEdit = async (row: any) => {
    router.push({
        path: '/content/channelFootage/officialaccountgraphics/detail',
        query: { type: 'edit', id: row.id, copy: 1 }
    });
};
// 删除
const onDel = async (row: any) => {
    // await groupMassOffical(id)
    // ElMessage.success('群发成功')
    state.row = row;
    DeletdialogRef.value.appDialog.title = '删除';
    DeletdialogRef.value.content = '确定删除该内容吗？';
    DeletdialogRef.value.appDialog.visible = true;
};
const onDelSubmit = async () => {
    await delOfficalDraft({ id: state.row.id });
    ElMessage.success('删除成功');
    reloadTable();
};
const renderBtn = (row: any) => {
    return (
        <>
            <el-button size="small" onClick={() => onQunFa(row)}>
                群发
            </el-button>
            <el-button size="small" onClick={() => onYuLan(row)}>
                预览
            </el-button>
            <el-button size="small" onClick={() => onEdit(row)}>
                编辑
            </el-button>
            <el-button size="small" onClick={() => onDel(row)}>
                删除
            </el-button>
        </>
    );
};
// 表格
const tableOption = [
    {
        prop: 'draft_title',
        label: '草稿标题',
        width: 200
    },
    {
        prop: 'article_detail',
        label: '内容',
        minWidth: 200,
        render({ row, column, index }) {
            return (
                <ArticleDetailItem
                    isLink={false}
                    index={index}
                    list={row.article_detail}
                    onSubmit={index => onChangeCollapse(index)}
                />
            );
        }
    },
    {
        prop: 'type_name',
        label: '图文类型',
        width: 200
    },
    {
        prop: 'created_uid_name',
        label: '创建人',
        width: 200
    },
    {
        prop: 'created_time',
        label: '创建时间',
        width: 200
    },

    {
        prop: 'operate',
        label: '操作',
        width: 200,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return renderBtn(row);
        }
    }
];
const fetchApi = () => {
    return getOfficialArticleList;
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};

// 同步时间
const SyncDilogRef = ref<any>(null);
const onUpdate = (type: string) => {
    // 1全部 2指定
    switch (type) {
        case '1':
            officialSync({ sync_type: 1 });
            break;
        case '2':
            SyncDilogRef.value.appDialog.visible = true;
            break;
    }
};
// 获取更新时间
const getUpdateTime = (time: string) => {
    state.syncTime = time;
};
// 去草稿箱
const toDraftbox = () => {
    router.push('/content/channelFootage/officialaccountgraphics/draftbox');
};
// 新建图文
const toCreate = () => {
    router.push('/content/channelFootage/officialaccountgraphics/detail');
};
const onCreate = async () => {
    // await createMassOfficialAccount(form)
    // form.type == 1 ? ElMessage.success('保存草稿成功') : form.type == 2 ? ElMessage.success('成功发送预览到目标手机微信') : ElMessage.success('群发成功')
};

const timer = setTimeout(() => {
    ElMessage.closeAll();
}, 1000 * 3);
onUnmounted(() => {
    // clearTimeout(timer)
});
// 预览
const onCancel = () => {
    appDialog.visible = false;
    state.preview_wx_user_id = [];
};
// 确定
const onYuLanSubmit = async () => {
    if (state.preview_wx_user_id.length === 0) {
        ElMessage.warning('请输入预览的帐号');
        return;
    }
    // 校验微信号格式
    const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;
    const isWxUser = state.preview_wx_user_id.every(item => reg.test(item));
    if (!isWxUser) {
        ElMessage.warning('请输入正确的微信号');
        return;
    }
    await previewOffical({ id: state.row.id, preview_wx_user_id: state.preview_wx_user_id });
    ElMessage.success('成功发送预览到目标手机微信');
    state.preview_wx_user_id.forEach(item => {
        state.previewWxUserIdList.includes(item) || state.previewWxUserIdList.push(item);
    });
    onCancel();
};
const appDialog = reactive({
    visible: false,
    title: '发送预览',
    width: '700px',
    cancel: onCancel,
    submit: onYuLanSubmit,
    cancelText: '取消',
    submitText: '确定'
});
</script>

<style scoped lang="scss">
.draftbox_container {
    display: flex;

    .draftbox_container_left {
        margin-right: 16px;
    }

    .draftbox_container_right {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }

        :deep(.article_detail) {
            display: flex;
            align-items: center;
            margin-bottom: 5px;

            .article_cover {
                min-width: 30px;
                max-width: 30px;
                min-height: 30px;
                max-height: 30px;
                margin-right: 10px;
                font-size: 30px;
            }

            .article_title {
                font-size: 14px;
                font-weight: 300;
                color: #33302d;

                &:hover {
                    color: #ff6b00;
                }
            }
        }
    }
}

.wrapper {
    padding: 45px 80px 0;
    min-height: 355px;
}

.title {
    text-align: center;
}

:deep(.wx_select) .el-input__icon {
    display: none;
}
</style>
<style lang="scss">
.wx_popper {
    display: none;
}
</style>
